//
// Created by Xu Xiao on 2022/9/10.
//

#ifndef ALGORITHM_22_1_SLN_K_Q2557_H
#define ALGORITHM_22_1_SLN_K_Q2557_H

#include <iostream>
#include <cstring>
#include <unordered_map>

using namespace std;

class Sln_K_Q2557 {
private:
    int n, a[1010]{}, b[1010]{}, cnt[1010]{};
    unordered_map<string, int> que;
    string name[1010];
    bool flag[1010]{};

    void work() {
        int rnd = 1, tm = n, cur = 0;
        int s = tm / 2;
        memset(flag, 1, sizeof(flag));
        while (tm > 1) {
            for (int i = 1; i < n; i++) {
                if (flag[a[i]] && flag[b[i]] && (cnt[a[i]] == 1 || cnt[b[i]] == 1)) {
                    if (cur == 0) {
                        cout << "Round #" << rnd << endl;
                    }
                    cur++;
                    tm--;
                    cnt[a[i]]--;
                    cnt[b[i]]--;
                    if (cnt[a[i]]) {
                        cout << name[a[i]] << " defeats " << name[b[i]] << endl;
                    } else if (cnt[b[i]]) {
                        cout << name[b[i]] << " defeats " << name[a[i]] << endl;
                    } else {
                        cout << name[b[i]] << " defeats " << name[a[i]] << endl;
                        cout << "Winner: " << name[b[i]] << endl;
                    }
                    flag[a[i]] = false;
                    flag[b[i]] = false;
                    if (cur == s) {
                        cur = 0;
                        rnd++;
                        s = tm / 2;
                        for (int j = 1; j <= n; j++) {
                            if (flag[j] && cnt[j]) {
                                cout << name[j] << " advances with wildcard" << endl;
                            }
                            flag[j] = (cnt[j] != 0);
                        }
                    }
                }
            }
        }
        printf("\n");
    }

public:
    explicit Sln_K_Q2557(int nums) {
        n = nums;
        for (int i = 1; i <= n; i++) {
            cin >> name[i];
            que[name[i]] = i;
        }
        string _s;
        int p;
        for (int i = 1; i < n; i++) {
            cin >> _s;
            p = que[_s];
            cnt[p]++;
            a[i] = p;
            cin >> _s;
            p = que[_s];
            cnt[p]++;
            b[i] = p;
        }
        work();
    }
};


#endif //ALGORITHM_22_1_SLN_K_Q2557_H
